﻿Public Class SXDataConvent

    ''' <summary>
    ''' 四信转义，向DTU发送数据时首先所有的将0xfd 转化为 0xfd 0xed  
    '''  然后将所有的0xfe 转化为0xfd 0xee
    ''' </summary>
    ''' <param name="res">要转义的数组</param>
    ''' <returns>返回数组</returns>
    ''' <remarks></remarks>
    Public Function Byte2Send(res As Byte()) As Byte()
        Try

            Dim L As New List(Of Byte)
        L.AddRange(res)
        For i = 0 To L.Count - 1
            If i > L.Count - 1 Then
                Exit For
            End If
            If (L(i) = &HFD) Then
                L.Insert(i + 1, &HED)
            ElseIf L(i) = &HFE Then
                L(i) = &HFD
                L.Insert(i + 1, &HEE)
            End If
        Next
            Return L.ToArray

        Catch ex As Exception
            Return res
        End Try
    End Function


    ''' <summary>
    ''' 四信转义：首先所有的将0xfd 0xed转化为 0xfd  然后将所有的0xfd 0xee转化为 0xfe
    ''' </summary>
    ''' <param name="res">需要转义的数组</param>
    ''' <returns>转义后数组</returns>
    ''' <remarks></remarks>
    Public Function Rec2Byte(res As Byte()) As Byte()
        Try


            If res.Length = 0 Then
                Return res
            End If
            Dim L As New List(Of Byte)
            L.AddRange(res)
            For i = 0 To L.Count - 2
                If i > L.Count - 2 Then
                    Exit For
                End If
                If L(i) = &HFD And L(i + 1) = &HED Then
                    L.RemoveAt(i + 1)
                ElseIf L(i) = &HFD And L(i + 1) = &HEE Then
                    L(i) = &HFE
                    L.RemoveAt(i + 1)
                End If
            Next
            Return L.ToArray
        Catch ex As Exception
            Return res
        End Try
    End Function
End Class
